include ApplicationHelper

class WishListsController < ApplicationController
  before_filter :load_session

  load_and_authorize_resource

  def load_session
    # sirve para que el poup de user sepa donde setar los valores elegidos
    session[:component_user_id] = 'wish_list_user_id'
    session[:component_user_name] = 'wish_list_user'
    session[:entity_caller] = "WISH_LIST"

    @localusers = User.search_selector("", params[:page])
  end


  def redirect_back
      redirect_back_or_default params[:url]
  end

  # GET /wish_lists
  # GET /wish_lists.xml
  def index
    save_redirect_back request.request_uri
    search_user_name = params[:search_user] || ""
    page = params[:page] || 1
    @wish_lists  = WishList.search(nil, search_user_name, "", nil, page)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @wish_lists }
    end
  end

  def wish_list_materials_index
    @wish_list = WishList.find(params[:id])

    if !(current_user.role?(:role_admin)) and current_user.id != @wish_list.user_id
      show_page_access_denied
    else
      save_redirect_back request.request_uri

      #se cargan los materiales para el popup
      #PabloR: desde que no se puede agregar materiales ya no es necesario.
      #@materials = Material.search("", -1, "", "", params[:page])

      search_title = params[:search_title] || ""
      wish_list_ids= []
      wish_list_ids << @wish_list.id      
      @materials_wish_lists = MaterialsWishList.search(wish_list_ids, search_title, params[:page])
    end
  end

  def wish_list_add_material
    #busco cual es el ultimo material definido para esta lista
    last_material_wish_list = MaterialsWishList.find(:first, :order => "order_list desc", :conditions => ["wish_list_id = ?",  params[:wish_list_id]])

    #obtengo las instancias de material y wish_list involucradas
    wish_list = WishList.find(params[:wish_list_id])
    material = Material.find(params[:material_id])

    #agrego el material a la lista
    material_wish_list = MaterialsWishList.new
    material_wish_list.material = material
    material_wish_list.wish_list = wish_list
    if last_material_wish_list.nil?
      material_wish_list.order_list = 1
    else
      material_wish_list.order_list = last_material_wish_list.order_list + 1
    end

      if material_wish_list.save
        flash[:notice] = t('lbl_material_add_wish_list_ok')
      else
        flash[:error] = t('lbl_material_add_wish_list_error')
      end
      redirect_back_or_default wish_list_materials_path
  end

  def wish_list_delete_material
    #se busca el registro asociado a esta lista-material
    wish_list_material = MaterialsWishList.find(params[:materials_wish_list_id])
    wish_list_material.destroy
    redirect_back_or_default wish_list_materials_path
  end

  def wish_list_up_material
    #se busca el registro asociado a esta lista-material
    wish_list_material = MaterialsWishList.find(params[:materials_wish_list_id])

    #busco el primer material con order < al registro elegido
    wish_list_material_prev = MaterialsWishList.find(:first,:order => "order_list DESC", :conditions => ["wish_list_id = ? and order_list < ?", wish_list_material.wish_list_id, wish_list_material.order_list])

    if !wish_list_material_prev.nil?
      #swap
      temp = wish_list_material.order_list
      wish_list_material.order_list = wish_list_material_prev.order_list
      wish_list_material_prev.order_list = temp
      #save
      wish_list_material.save
      wish_list_material_prev.save
    end

    redirect_back_or_default wish_list_materials_path
  end

  def wish_list_down_material
    #se busca el registro asociado a esta lista-material
    wish_list_material = MaterialsWishList.find(params[:materials_wish_list_id])

    #busco el primer material con order > al registro elegido
    wish_list_material_next = MaterialsWishList.find(:first,:order => "order_list", :conditions => ["wish_list_id = ? and order_list > ?", wish_list_material.wish_list_id, wish_list_material.order_list])

    if !wish_list_material_next.nil?
      #swap
      temp = wish_list_material.order_list
      wish_list_material.order_list = wish_list_material_next.order_list
      wish_list_material_next.order_list = temp
      #save
      wish_list_material.save
      wish_list_material_next.save
    end

    redirect_back_or_default wish_list_materials_path
  end

  # GET /wish_lists/1
  # GET /wish_lists/1.xml
  def show
    @wish_list = WishList.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @wish_list }
    end
  end

  # GET /wish_lists/new
  # GET /wish_lists/new.xml
  def new
    @wish_list = WishList.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @wish_list }
    end
  end

  # GET /wish_lists/1/edit
  def edit
    @wish_list = WishList.find(params[:id])
    @localusers = User.search_selector("", params[:page])
  end

  # POST /wish_lists
  # POST /wish_lists.xml
  def create
    error = false
    if params[:wish_list][:type_list] != WishList::TYPE_SIMPLE && params[:wish_list][:user_id] != "" &&
       0 < WishList.count(:conditions => ["user_id = ? and type_list = ?", params[:wish_list][:user_id], params[:wish_list][:type_list]])
        flash[:error] = "El usuario no puede tener dos listas de este tipo #{t(params[:wish_list][:type_list])}"
        error = true
    else
      @wish_list = WishList.new(params[:wish_list])
      if !@wish_list.save
        error = true
      end
    end

    respond_to do |format|
      if !error
        flash[:notice] = t('msg_record_successfully_created')
        format.html { redirect_to(@wish_list) }
        format.xml  { render :xml => @wish_list, :status => :created, :location => @wish_list }
      else
        if params[:wish_list][:user_id] != ""
          @wish_list_user = User.find(params[:wish_list][:user_id]).email
        end
        format.html { render :action => "new" }
        format.xml  { render :xml => @wish_list.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /wish_lists/1
  # PUT /wish_lists/1.xml
  def update
    puts "las parms es: #{params}"
    error = false
    if params[:wish_list][:type_list] != WishList::TYPE_SIMPLE && params[:wish_list][:user_id] != "" &&
       0 < WishList.count(:conditions => ["id <> ? and user_id = ? and type_list = ?", params[:id], params[:wish_list][:user_id], params[:wish_list][:type_list]])
        flash[:error] = "El usuario no puede tener dos listas de este tipo #{t(params[:wish_list][:type_list])}"
        error = true
    else
      @wish_list = WishList.find(params[:id])
      if !@wish_list.update_attributes(params[:wish_list])
        error = true
      end
    end

    respond_to do |format|
      if !error
        flash[:notice] = t('msg_record_successfully_updated')
        format.html { redirect_to(@wish_list) }
        format.xml  { head :ok }
      else
        if params[:wish_list][:user_id] != ""
          @wish_list_user = User.find(params[:wish_list][:user_id]).email
        end
        format.html { render :action => "edit" }
        format.xml  { render :xml => @wish_list.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /wish_lists/1
  # DELETE /wish_lists/1.xml
  def destroy
    @wish_list = WishList.find(params[:id])
    @wish_list.destroy

    respond_to do |format|
      format.html { redirect_to(wish_lists_url) }
      format.xml  { head :ok }
    end
  end
end
